<template>
  <el-autocomplete
    class="w-100"
    v-bind="$attrs"
    popper-class="customer-autocomplete"
    :value="value"
    :fetch-suggestions="throttleGetData"
    @input="handleInput"
    @select="handleSelect"
  >
    <template slot-scope="props">
      <div>{{ props.item.customer_name }}</div>
      <small class="text-muted">
        {{ (props.item.address || '') + (props.item.address_detail || '') }}
      </small>
    </template>
  </el-autocomplete>
</template>

<script>
import { addressCut, throttle } from '@vimi/utils-tool'

export const fields = [
  'register_no',
  'id_card',
  'customer_name',
  'corp_name',
  'address_code',
  'address_detail',
  'business_scope',
  'org_class',
  'org_class_name',
  'parent_main_business',
  'main_business',
  'mobile_no',
]
export default {
  components: {},
  props: {
    value: String,
    industry: { type: Boolean, default: false },
    packageId: String,
  },
  model: {
    prop: 'value',
    event: 'change',
  },
  data() {
    return {
      loading: false,
      tableName: 'datum_customer_info_warehouse',
      params: {
        index: 1,
        size: 30,
        customer_name: '',
        project_type_id: '',
      },
      order: {
        create_time: 'desc',
      },
    }
  },
  computed: {
    user() {
      return this.$store.getters.user
    },
    queryAddressCode() {
      return this.user.queryAddressCode || this.user.addressCode
    },
  },
  watch: {},
  created() {},
  mounted() {},
  methods: {
    throttleGetData: throttle(500, function (queryString, cb) {
      this.getWarehouse(queryString, cb)
    }),

    handleSelect(val) {
      this.$emit('change', val.customer_name)
      this.$emit('select', val)
    },
    handleInput(val) {
      this.$emit('change', val)
    },
    async getWarehouse(queryString = '', cb) {
      queryString = queryString.trim()
      let data = []
      if (this.params.customer_name === queryString) {
        return cb(data)
      }
      this.params.customer_name = queryString
      this.params.groupFields = ['register_no', 'id_card']
      this.params.fields = [...fields, 'address']
      if (this.industry) {
        this.params['submit_type.eq'] = 2
      } else {
        this.params.orWhereAndTemplate = 2
        this.params['orWhereAnd.submit_type.eq'] = 2
        this.params['orWhereAnd.service_id.neq'] = 1

        this.params['orWhereAnd.submit_type.in'] = 1
        this.params['orWhereAnd.address_code.endlike'] = addressCut(this.queryAddressCode)
        this.params['orWhereAnd.project_type_id.eq'] = this.packageId
      }
      this.loading = true
      const [res] = await this.$utils.promise(
        this.$api.getData('credit', this.tableName, this.params, this.order)
      )
      this.loading = false
      data = (res && res.data && res.data.data) || []
      cb(data)
    },
  },
}
</script>

<style lang="scss" scoped></style>
